package com.exercise.AndroidCamera;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import com.exercise.AndroidCamera.SlideListAdapter.deleteUserInfoAsync;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TableRow.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;
/*
기능 : 친구관리
작성 : 하드캔
완료일 : 2014.09.26 
	*/
public class ManageFriendActivity extends BaseActivity implements OnItemClickListener{

	Intent mIntent;
	String userID;
	String friendID;
	
	int numberOfBoard=6, i;
	int friendnum=0;
	LinearLayout linLayout;
	LinearLayout LL=null;
	int[] imgResource;
	int flag = 0;

	private ListView list;
	ArrayList<String> friendArray;
	ArrayList <String> checkedValue;

	TextView friendView;
	Button deleteFriend;
	Button findFriendInfo;
	LinearLayout friendListLayout, tmpbtnLayout;
	LinearLayout[] friendOneLayout;
	
	FriendListAdapter adapter;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_manage_friend);
			
		friendArray = new ArrayList<String>();

		userID = getIntent().getExtras().getString("userID");
		friendID = getIntent().getExtras().getString("friendID");
		linLayout = (LinearLayout) findViewById(R.id.container);
			
		friendListLayout = (LinearLayout) findViewById(R.id.friendListLayout);
		
		getActionBar().setTitle("Post Memories");
		getActionBar().setDisplayShowHomeEnabled(false);
		getActionBar().setDisplayHomeAsUpEnabled(true);


			friendListAsync friendList = new friendListAsync();
			friendList.execute();
	}
	
	
	//comment 
	protected String[] friend_list_read(String location_id){
		String pString = null;
		HttpURLConnection conn = null;
		BufferedReader br = null;
		
		String[] result = new String[2];
		result[0] = "error"; //JSON flag
		result[1] = null; //message
		
		try{
       	StringBuilder builder = new StringBuilder();
       	
       	URL url = new URL("http://54.199.194.197/list_friend.php");
       	conn = (HttpURLConnection)url.openConnection();
       	
       	if(conn != null){
       		conn.setConnectTimeout(150000);	
       		conn.setReadTimeout(150000);
       		conn.setDefaultUseCaches(false); 
           	conn.setDoInput(true); 
           	conn.setDoOutput(true);  
           	conn.setRequestMethod("POST"); 
           	conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
              
         	StringBuffer buffer = new StringBuffer();
         	buffer.append("user_id").append("=").append(userID);

            OutputStreamWriter outStream = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            PrintWriter writer = new PrintWriter(outStream);
            writer.write(buffer.toString());
            writer.flush();
            
            InputStreamReader inputStream = new InputStreamReader(conn.getInputStream(), "UTF-8"); 
            br = new BufferedReader(inputStream);
              
           	String line;
           	while((line = br.readLine()) != null){
           	   builder.append(line);
           	}
              
           	br.close();
           	
           	pString =  builder.toString();
           	
           	JSONObject jObject = new JSONObject(pString);
           	JSONArray friendObject = new JSONArray(jObject.getString("friend_id"));
           	
           	for(int i=0; i<friendObject.length(); i++){
           		friendArray.add(friendObject.getString(i));
           		Log.d("friendArray", friendArray.get(i));
           	}
           	
       	}else{
       		
       		throw new Exception("network error");
       	}
       	
       }catch(SocketTimeoutException se){
       	
       	result[1] = "network error";
       	
       }catch(Exception e){
       	
       	result[1] = e.getMessage();
       	
       }finally{
       	
       	if(conn != null)
       		conn.disconnect();

       	if(br != null){
       		try {
       			br.close();
				} catch (Exception e2) {
					// TODO: handle exception
					result[1] = e2.getMessage();
				}
       	}
       }
       return result;
	}
	
	
	public class friendListAsync extends AsyncTask<String, String, String> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}
		@Override
		protected String doInBackground(String... params) {
			friend_list_read("0");
			return null;
		}
		@Override
		protected void onPostExecute(String result) {
			friendListLayout.removeAllViews();
			friendOneLayout = new LinearLayout[friendArray.size()];
			Typeface tf  = Typeface.createFromAsset(ManageFriendActivity.this.getAssets(), "fonts/whitechok.ttf");
			for(friendnum=0; friendnum < friendArray.size(); friendnum++){
				tmpbtnLayout = new LinearLayout(ManageFriendActivity.this);
				tmpbtnLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
				tmpbtnLayout.setOrientation(LinearLayout.HORIZONTAL);
				friendView = new TextView(ManageFriendActivity.this);
				friendView.setText(friendArray.get(friendnum).toString());
				friendView.setTypeface(tf);
				friendView.setTextSize(20);
				deleteFriend = new Button(ManageFriendActivity.this);
				deleteFriend.setTag(friendnum);
				deleteFriend.setBackgroundResource(R.drawable.delete);
				deleteFriend.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(final View v) {
						// TODO Auto-generated method stub
						new AlertDialog.Builder(ManageFriendActivity.this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("친구 삭제").setMessage("친구를 삭제하시겠습니까?")
						.setNeutralButton("아니오", null)
						.setPositiveButton("예", new DialogInterface.OnClickListener()
					   {
					     @Override
					     public void onClick( DialogInterface dialog, int which )
					     {
					    		friendID = friendArray.get((Integer)v.getTag()).toString();
								deleteFriendAsync deletefriend = new deleteFriendAsync();
								deletefriend.execute();
					     }
					   }).show(); 
					}
				});
				findFriendInfo = new Button(ManageFriendActivity.this);
				findFriendInfo.setBackgroundResource(R.drawable.info);
				findFriendInfo.setTag(friendnum);
				findFriendInfo.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						Intent mintent = new Intent(ManageFriendActivity.this, FriendInfoActivity.class);
				    	mintent.putExtra("userID", userID);
				    	mintent.putExtra("friendID", friendArray.get((Integer)v.getTag()).toString());
				    	startActivity(mintent);
					}
				});
				tmpbtnLayout.addView(findFriendInfo);
				tmpbtnLayout.addView(deleteFriend);
				tmpbtnLayout.setGravity(Gravity.RIGHT);
				tmpbtnLayout.setPadding(10, 10, 10, 10);
				friendOneLayout[friendnum] = new LinearLayout(ManageFriendActivity.this);
				friendOneLayout[friendnum].setLayoutParams(new LayoutParams (LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
				friendOneLayout[friendnum].setOrientation(LinearLayout.HORIZONTAL);
				friendOneLayout[friendnum].setPadding(20,20,20,20);
				friendOneLayout[friendnum].setBackgroundResource(R.drawable.round_background_reverse);
				friendOneLayout[friendnum].setGravity(Gravity.CENTER);
				friendOneLayout[friendnum].addView(friendView,0);
				friendOneLayout[friendnum].addView(tmpbtnLayout,1);
				friendListLayout.addView(friendOneLayout[friendnum], i);
			}
			
			
			super.onPostExecute(result);
		}
		@Override
		protected void onCancelled() {
			super.onCancelled();
		}
	}
	
	 @Override
	 public void onItemClick(AdapterView arg0, View v, int position, long arg3) {
	  // TODO Auto-generated method stub
	 }
		

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	     
	    switch(item.getItemId()){
	    
	    case android.R.id.home:
            onBackPressed();
            break;

	    default:
	        return false;
	    }
	    return true;
	}
	
	
	public class deleteFriendAsync extends AsyncTask<String, String, String> {
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}
		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			friend_list_delete(ManageFriendActivity.this, friendID);
			return null;
		}
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			flag=1;
			onResume();
			super.onPostExecute(result);
		}
	}
	
	@Override
	protected void onResume() {
		if(flag==1) {
			friendArray.clear();
			friendListAsync friendList = new friendListAsync();
			friendList.execute();
		} 
		super.onResume();
	}
	
	protected String[] friend_list_delete(Context context, String friend_id){
		String pString = null;
		HttpURLConnection conn = null;
		BufferedReader br = null;
		
		String[] result = new String[2];
		result[0] = "error"; //JSON flag
		result[1] = null; //message
		
		try{
       	StringBuilder builder = new StringBuilder();
       	
       	URL url = new URL("http://54.199.194.197/delete_friend.php");
       	conn = (HttpURLConnection)url.openConnection();
       	
       	if(conn != null){
       		conn.setConnectTimeout(150000);	
       		conn.setReadTimeout(150000);
       		conn.setDefaultUseCaches(false); 
           	conn.setDoInput(true); 
           	conn.setDoOutput(true);  
           	conn.setRequestMethod("POST"); 
           	conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
              
         	StringBuffer buffer = new StringBuffer();
         	buffer.append("user_id").append("=").append(userID).append("&");
         	buffer.append("friend_id").append("=").append(friend_id);

            OutputStreamWriter outStream = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            PrintWriter writer = new PrintWriter(outStream);
            writer.write(buffer.toString());
            writer.flush();
            
            InputStreamReader inputStream = new InputStreamReader(conn.getInputStream(), "UTF-8"); 
            br = new BufferedReader(inputStream);
              
           	String line;
           	while((line = br.readLine()) != null){
           	   builder.append(line);
           	}
              
           	br.close();
           	
           	pString =  builder.toString();
           	Log.d("pString in read comment", pString);
           	
           	JSONObject jObject = new JSONObject(pString);
           	JSONArray friendObject = new JSONArray(jObject.getString("friend_id"));
           	
           	for(int i=0; i<friendObject.length(); i++){
           		friendArray.add(friendObject.getString(i));
           	}
           	
       	}else{
       		
       		throw new Exception("network error");
       	}
       	
       }catch(SocketTimeoutException se){
       	
       	result[1] = "network error";
       	
       }catch(Exception e){
       	
       	result[1] = e.getMessage();
       	
       }finally{
       	
       	if(conn != null)
       		conn.disconnect();

       	if(br != null){
       		try {
       			br.close();
				} catch (Exception e2) {
					// TODO: handle exception
					result[1] = e2.getMessage();
				}
       	}
       }
       return result;
	}
}
